class SiteHeartBeat::Available < SiteHeartBeat
  
  belongs_to :site_heart_beat_daily_stat, :counter_cache => :available_site_heart_beats_count

  validates_presence_of :site_heart_beat_daily_stat_id,
    :started_at,
    :ended_at

  def send_email!(options = {})
    if site_health_setting.allow_email?
      UserMailer.deliver_send_site_health_of_available self,options if Rails.env != 'test'
      user.add_emails_count!
      site_health_setting.add_emails_count!
    end
  end

  def send_sm!
    if site_health_setting.allow_sms? and user.mobile?
      Sm.create!( :user => user,
        :content =>  "【#{site_heart_beat_daily_stat.site_health_setting.name}】的故障已经恢复，目前的响应时间是#{response_time}ms。今日的健康度是#{site_heart_beat_daily_stat.health_degree}%（#{site_heart_beat_daily_stat.available_site_heart_beats_count}次可用/#{site_heart_beat_daily_stat.unavailable_site_heart_beats_count}次故障），平均响应时间#{site_heart_beat_daily_stat.avg_response_time}ms，最快响应时间#{site_heart_beat_daily_stat.the_fastest_heart_beat.response_time}ms，最慢响应时间#{site_heart_beat_daily_stat.the_slowest_heart_beat.response_time}ms【麦吐司网】",
        :pri => 2) if Rails.env != 'test'
      user.add_sms_count!
      site_health_setting.add_sms_count!
    end
  end
  
  def before_save
    self.response_time = (ended_at - started_at)*1000
  end

  def after_save
    site_heart_beat_daily_stat.reset_availables_stat!
    logger.debug "今日次数：#{site_heart_beat_daily_stat.available_site_heart_beats_count}"    
    logger.debug "今日失败次数：#{site_heart_beat_daily_stat.unavailable_site_heart_beats_count}"    
    if pre_one.present? and pre_one.is_a?(SiteHeartBeat::Unavailable)      
      send_email
      send_sm
    end
  end

  def type_name
    '可用'
  end
end
